﻿using King.Box.Utils.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;

namespace King.Box.WebApi.Binder
{
    public class ModelBinderFromUri<T> : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (actionContext == null || bindingContext == null)
                return false;

            var uri = HttpUtility.UrlDecode(actionContext.Request.RequestUri.Query.ToString());
            if (string.IsNullOrEmpty(uri))
                return false;

            string jsonData = uri;
            switch (actionContext.Request.Content.Headers.ContentType.MediaType.ToLower())
            {
                case "application/json":
                    if (jsonData.StartsWith("?"))
                        jsonData = jsonData.Remove(0, 1);
                    break;
                case "application/x-www-form-urlencoded":
                    if (jsonData.StartsWith("?"))
                        jsonData = jsonData.Remove(0, 1);

                    string temp;
                    var paramDic = Util.ParseQueryStringToDictionary(jsonData);
                    paramDic.TryGetValue(bindingContext.ModelName, out temp);
                    jsonData = temp;
                    break;
                default:
                    break;
            }

            try
            {
                T model = JsonConvert.DeserializeObject<T>(jsonData);
                bindingContext.Model = model;
            }
            catch (JsonReaderException ex)
            {
                throw new Exception($"value of {bindingContext.ModelName} is not a validate json", ex);
            }
            return bindingContext.Model != null;
        }
    }
}
